package com.mqtt.ctwingmqtt;

public class Main {
    public static void main(String[] args) {
        String s = convertAddress("4345461811");
        System.out.println(s); // 输出：78563412000000
        String s1 = convertToHex(100);
        System.out.println(s1);

        String input = "6846AAAAAAAAAAAAAA0406AC04020103E8";
        String result = calculateCheckCode(input);
        System.out.println("校验码: " + result); // 输出应为 FE
    }
    public static String convertToHex(int num) {
        int result = num * 10;
        return String.format("%04X", result);
    }

    private static String convertAddress(String address) {
        if (address == null || address.isEmpty()) {
            throw new IllegalArgumentException("地址不能为空");
        }

        // 按2位分割字符串
        int length = address.length();
        StringBuilder convertedAddress = new StringBuilder();

        // 分割为每两位的块，并逆序排列
        for (int i = length - 2; i >= 0; i -= 2) {
            String pair = address.substring(i, i + 2);
            convertedAddress.append(pair);
        }

        // 处理奇数长度的情况（最后一位单独处理）
        if (length % 2 != 0) {
            char lastChar = address.charAt(0); // 取第一位（如果总长度为奇数）
            convertedAddress.append(lastChar);
        }

        // 将结果转换为字符串，并补足到14位
        String result = convertedAddress.toString();
        if (result.length() > 14) {
            result = result.substring(0, 14);
        } else {
            result = String.format("%-" + 14 + "s", result).replace(' ', '0');
        }

        return result;
    }

    public static String calculateCheckCode(String hexData) {
        // 1. 验证输入是否为有效十六进制
        if (!hexData.matches("[0-9a-fA-F]+")) {
            throw new IllegalArgumentException("输入必须是有效的十六进制字符串");
        }

        // 2. 将十六进制字符串转换为字节数组
        byte[] bytes = hexStringToByteArray(hexData);

        // 3. 累加所有字节的值，忽略溢出（取低8位）
        int sum = 0;
        for (byte b : bytes) {
            sum += (b & 0xFF); // 将字节转换为无符号整数
        }
        int checkCode = sum & 0xFF; // 取低8位

        // 4. 将校验码转换为两位大写十六进制字符串
        return String.format("%02X", checkCode);
    }

    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}